package com.enation.app.javashop.core.trade.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.enation.app.javashop.core.base.CachePrefix;
import com.enation.app.javashop.core.client.goods.GoodsClient;
import com.enation.app.javashop.core.client.member.MemberAddressClient;
import com.enation.app.javashop.core.client.member.ShipTemplateClient;
import com.enation.app.javashop.core.goods.GoodsErrorCode;
import com.enation.app.javashop.core.goods.model.dto.ShipCalculateDTO;
import com.enation.app.javashop.core.goods.model.vo.CacheGoods;
import com.enation.app.javashop.core.goodssearch.service.impl.GoodsShipCalculator;
import com.enation.app.javashop.core.goodssearch.service.impl.ShipFeeCalculator;
import com.enation.app.javashop.core.goodssearch.service.impl.ShipTimeCalculator;
import com.enation.app.javashop.core.member.model.dos.MemberAddress;
import com.enation.app.javashop.core.shop.model.dos.ShipLocalTemplateVO;
import com.enation.app.javashop.core.shop.model.dos.TemplateFeeSetting;
import com.enation.app.javashop.core.shop.model.dto.ShipTemplateChildDTO;
import com.enation.app.javashop.core.shop.model.vo.ShipTemplateChildBuyerVO;
import com.enation.app.javashop.core.shop.model.vo.ShipTemplateVO;
import com.enation.app.javashop.core.trade.TradeErrorCode;
import com.enation.app.javashop.core.trade.cart.model.enums.CartSourceType;
import com.enation.app.javashop.core.trade.cart.model.enums.CartType;
import com.enation.app.javashop.core.trade.cart.model.vo.CartSkuVO;
import com.enation.app.javashop.core.trade.cart.model.vo.CartVO;
import com.enation.app.javashop.core.trade.cart.model.vo.PromotionRule;
import com.enation.app.javashop.core.trade.cart.model.vo.ShipWayVO;
import com.enation.app.javashop.core.trade.order.model.enums.ShipTypeEnum;
import com.enation.app.javashop.core.trade.order.service.CheckoutParamManager;
import com.enation.app.javashop.core.trade.order.service.ShippingManager;
import com.enation.app.javashop.framework.cache.Cache;
import com.enation.app.javashop.framework.context.UserContext;
import com.enation.app.javashop.framework.exception.ServiceException;
import com.enation.app.javashop.framework.logs.Debugger;
import com.enation.app.javashop.framework.security.model.Buyer;
import com.enation.app.javashop.framework.util.CurrencyUtil;
import com.enation.app.javashop.framework.util.GeoUtils;
import com.enation.app.javashop.framework.util.StringUtil;
import com.google.common.collect.Maps;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.ss.formula.functions.T;
import org.gavaghan.geodesy.GlobalCoordinates;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 运费计算业务层实现类
 *
 * @author Snow create in 2018/4/8
 * @version v2.0
 * @since v7.0.0
 */
@Service
public class ShippingManagerImpl implements ShippingManager {

    protected final Log logger = LogFactory.getLog(this.getClass());

    @Autowired
    private GoodsClient goodsClient;

    @Autowired
    private ShipTemplateClient shipTemplateClient;

    @Autowired
    private MemberAddressClient memberAddressClient;

    @Autowired
    private CheckoutParamManager checkoutParamManager;

    @Autowired
    private ShipFeeCalculator shipFeeCalculator;

    @Autowired
    private ShipTimeCalculator shipTimeCalculator;

    @Autowired
    private Cache cache;

    @Autowired
    private Debugger debugger;


    /**
     * 获取购物车快递配送费
     *
     * @param cartVO 购物车
     * @param areaId 地区id
     * @return
     */
    @Override
    public Double getShipPrice(CartVO cartVO, Integer areaId) {
        //最终运费
        double finalShip = 0;

        // 商品叠加模式
        //finalShip = simpleMode(cartVO);
        // 组合模式
        finalShip = complexMode(cartVO);

        if (logger.isDebugEnabled()) {
            logger.debug("最终运费金额计算：" + finalShip);

        }
        return finalShip;
    }

    /**
     * 快递组合模式计费
     *
     * 多个商品，既有统一运费，又有运费模板，则统一运费和模板计费取最大值
     * 说明：先将使用统一运费和运费模板的商品分开计算，再取二者较大的值，作为最终运费。
     * - 统一运费取最大值：A、B、C 统一运费分别为1元，2元和3元，同时购买A+B+C，则统一运费为：3元。
     * ﻿
     * - 运费模板运费：x = x1首费最贵的模板（首费+续费） + x2其他模板（从续费开始算）。
     *
     * @param cartVO
     * @return
     */
    private double complexMode(CartVO cartVO) {
        //最终运费
        double finalShip = 0;

        List<CartSkuVO> cartSkuVOS = cartVO.getSkuList();
        // 店铺所有快递模板
        Map<Integer, ShipTemplateChildDTO> shipTemplateChildMap = cartVO.getShipTemplateChildMap();
        List<ShipTemplateChildDTO> selectedTemp = new ArrayList<>();
        // 最高统一运费
        Double unifiedPrice = 0.0;
        Double totalWeight = 0.0;
        Double totalNum = 0.0;
        for (CartSkuVO cartSkuVO : cartSkuVOS) {
            //购物车商品没有被选中的话，则不进行处理
            if (cartSkuVO.getChecked() == 0) {
                continue;
            }
            // 统一运费
            if (cartSkuVO.getFreightPricingWay() != null && cartSkuVO.getFreightPricingWay() == 0) {
                unifiedPrice = cartSkuVO.getFreightUnifiedPrice() > unifiedPrice ? cartSkuVO.getFreightUnifiedPrice() : unifiedPrice;
            }

            //获取当前商品的运费模版
            ShipTemplateChildDTO temp = shipTemplateChildMap.get(cartSkuVO.getSkuId());
            if (temp != null && !selectedTemp.contains(temp)) {
                selectedTemp.add(temp);
            }

            //计算基数  重量/数量
            totalWeight += CurrencyUtil.mul(cartSkuVO.getGoodsWeight(), cartSkuVO.getNum());
            totalNum += (double) cartSkuVO.getNum();
        }

        // 单店商品重量和件数汇总
        cartVO.setTotalWeight(totalWeight);
        cartVO.setTotalNum(totalNum);
        // 按照组合模式规则进行汇算
        // 1、只有统一运费
        if (CollectionUtils.isEmpty(selectedTemp)) {
            return unifiedPrice;
        }
        // 2、运费模板
        if (!CollectionUtils.isEmpty(selectedTemp)) {
            // 单个模板
            if (selectedTemp.size() == 1) {
                ShipTemplateChildDTO temp = selectedTemp.get(0);
                // 首重/首件费用
                double shipPrice = temp.getFirstPrice();

                double purchase = temp.getType() == 1 ? totalWeight : totalNum;
                //是否需要计算 续重/续件
                if (temp.getFirstCompany() < purchase) {
                    //重量 / 续重=续重金额的倍数
                    double count = (purchase - temp.getFirstCompany()) / temp.getContinuedCompany();
                    //向上取整计算为运费续重倍数
                    count = Math.ceil(count);
                    // 运费 = 首重价格+续重倍数*续重费用
                    shipPrice = CurrencyUtil.add(shipPrice,
                            CurrencyUtil.mul(count, temp.getContinuedPrice()));
                    if (logger.isDebugEnabled()) {
                        logger.debug("续重/续件 费用：" + shipPrice);
                    }

                }
                finalShip = shipPrice;
            }
            // 多个模板
            else {
                // 计算首重最大值
                List<ShipTemplateChildDTO> temps = selectedTemp.stream().sorted(Comparator.comparing(ShipTemplateChildDTO::getFirstPrice).reversed())
                        .collect(Collectors.toList());
                double shipPrice = temps.get(0).getFirstPrice();

                // 续重使用第二个模板
                ShipTemplateChildDTO continueTemp = temps.get(1);
                double purchase = continueTemp.getType() == 1 ? totalWeight : totalNum;

                //重量 / 续重=续重金额的倍数
                double count = (purchase - continueTemp.getFirstCompany()) / continueTemp.getContinuedCompany();
                //向上取整计算为运费续重倍数
                count = Math.ceil(count);
                // 运费 = 首重价格+续重倍数*续重费用
                shipPrice = CurrencyUtil.add(shipPrice,
                        CurrencyUtil.mul(count, continueTemp.getContinuedPrice()));
                // 总运费
                finalShip=shipPrice;
            }
        }
        // 统一运费和模板运费对比取大值
        finalShip=finalShip>unifiedPrice?finalShip:unifiedPrice;
        return finalShip;
    }

    /**
     * 快递叠加模式计费
     * @param cartVO
     * @return
     */
    private double simpleMode(CartVO cartVO) {
        //最终运费
        double finalShip = 0;

        List<CartSkuVO> cartSkuVOS = cartVO.getSkuList();

        for (CartSkuVO cartSkuVO : cartSkuVOS) {
            //购物车商品没有被选中的话，则不进行处理
            if (cartSkuVO.getChecked() == 0) {
                continue;
            }
            if (cartSkuVO.getFreightPricingWay() != null && cartSkuVO.getFreightPricingWay() == 0) {
                finalShip += cartSkuVO.getFreightUnifiedPrice();
                continue;
            }
            //获取购物车 运费模版 映射
            Map<Integer, ShipTemplateChildDTO> map = cartVO.getShipTemplateChildMap();
            //获取当前商品的运费模版
            ShipTemplateChildDTO temp = map.get(cartSkuVO.getSkuId());
            if (temp == null) {
                continue;
            }

            //运费金额
            double shipPrice = temp.getFirstPrice();
            if (logger.isDebugEnabled()) {
                logger.debug("shipPrice：" + shipPrice);
            }

            //计算基数  重量/数量
            Double purchase;
            // 1 重量算运费
            if (temp.getType() == 1) {
                purchase = CurrencyUtil.mul(cartSkuVO.getGoodsWeight(), cartSkuVO.getNum());
            }
            // 2 计件算运费
            else {
                purchase = (double) cartSkuVO.getNum();
            }
            //是否需要计算 续重/续件
            if (temp.getFirstCompany() < purchase) {
                //重量 / 续重=续重金额的倍数
                double count = (purchase - temp.getFirstCompany()) / temp.getContinuedCompany();
                //向上取整计算为运费续重倍数
                count = Math.ceil(count);
                // 运费 = 首重价格+续重倍数*续重费用
                shipPrice = CurrencyUtil.add(shipPrice,
                        CurrencyUtil.mul(count, temp.getContinuedPrice()));
                if (logger.isDebugEnabled()) {
                    logger.debug("续重费用：" + shipPrice);
                }

            }
            finalShip = CurrencyUtil.add(finalShip, shipPrice);


        }
        return finalShip;
    }

    /**
     * 快递费用计算
     * 202020518 by JFENG 快递费计算规则
     *
     * @param cartList 购物车集合
     */
    @Override
    public void setShippingPrice(List<CartVO> cartList) {
        MemberAddress address = getUserCurrentAddress();
        // 衢山镇快递费特殊处理
        if (address == null) {
            CartVO cartVo = cartList.get(0);
            cartVo.setAllowGlobal(1);
            cartVo.getPrice().setFreightPrice(0.0);
            cartVo.getPrice().setIsFreeFreight(0);
            cartVo.setShippingTypeName("用户选择收货地址");
            return;
        }

        // 衢山镇额外收取快递费
        // String specialArea = address.getAddr()+address.getTown();
        //
        // if (specialArea.contains("衢山") && !specialArea.contains("衢山大道")) {
        //     calSpecialAreaFreightPrice(cartList);
        //     return;
        // }

        // 社区团购订单检查快递区域
        this.checkTownArea(address, cartList);

        // 检测不在配送区域的货品
        Integer areaId = address.actualAddress();
        this.checkArea(cartList, areaId);

        for (CartVO cartVo : cartList) {
            // 快递费用
            if (cartVo.getAllowGlobal() == 1) {
                List<PromotionRule> ruleList = cartVo.getRuleList();
                // 如果满减满赠免邮则不计算邮费
                if (StringUtil.isNotEmpty(ruleList)) {
                    boolean flag = false;
                    for (PromotionRule rule : ruleList) {
                        if (rule != null && rule.getFreeShipping()) {
                            flag = true;
                            break;
                        }
                    }
                    if (flag) {
                        return;
                    }
                }

                double finalShip = this.getShipPrice(cartVo, areaId);
                cartVo.getPrice().setFreightPrice(finalShip);
                cartVo.getPrice().setGlobalFreightPrice(finalShip);
                if (finalShip > 0) {
                    cartVo.getPrice().setIsFreeFreight(0);
                }
                cartVo.setShippingTypeName("运费");
            } else {
                // 如果不支持快递配送 需要设置默认数据
                cartVo.getPrice().setFreightPrice(0.0);
                cartVo.getPrice().setIsFreeFreight(0);
                cartVo.setShippingTypeName("不支持快递");
            }
        }
    }

    private void calSpecialAreaFreightPrice(List<CartVO> cartList) {
        logger.info("衢山到家运费计算-不计免邮");
        for (CartVO cartVo : cartList) {
            // 快递费用
            if (cartVo.getAllowGlobal() == 1) {
                List<PromotionRule> ruleList = cartVo.getRuleList();

                double finalShip = 3;
                cartVo.getPrice().setFreightPrice(finalShip);
                cartVo.getPrice().setGlobalFreightPrice(finalShip);
                if (finalShip > 0) {
                    cartVo.getPrice().setIsFreeFreight(0);
                }
                cartVo.setShippingTypeName("运费");
                if(!CollectionUtils.isEmpty(ruleList)){
                    // 衢山不支持免邮优惠
                    for (PromotionRule promotionRule : ruleList) {
                        if(promotionRule!=null){
                            promotionRule.setFreeShipping(false);
                        }
                    }
                }
            } else {
                // 如果不支持快递配送 需要设置默认数据
                cartVo.getPrice().setFreightPrice(0.0);
                cartVo.getPrice().setIsFreeFreight(0);
                cartVo.setShippingTypeName("不支持快递");
            }
        }
    }

    /**
     * 社区团购地址黑名单判断 第五级地址
     * @param address
     * @param cartList
     */
    private void checkTownArea(MemberAddress address, List<CartVO> cartList) {
        if (CollectionUtils.isEmpty(cartList)) {
            return;
        }
        CartVO cartVO = cartList.get(0);
        if (cartVO.getCartSourceType().equals(CartSourceType.SHETUAN_CART.name())) {
            String addr = address.getAddr();
            // 1.收货地址城市【不在】卖家所在城市
            if (StringUtils.isNotEmpty(cartVO.getCity()) &&
                    !(cartVO.getCity().contains(address.getProvince()) || cartVO.getCity().contains(address.getCity()))) {
                cartVO.setAllowCreateOrder(false);
                cartVO.setDispatchMsg("【不支持快递到家】:收货地址城市【不在】卖家所在城市,"+cartVO.getCity());
            }
            // 2.收货地址城市【在】卖家所在城市，但是第五级地址【在】黑名单之中
            String key = CachePrefix.TOWN_RESTRICT.getPrefix() + cartVO.getSellerId();
            List<Map<String, List<String>>> mapList = JSON.parseObject((String) cache.get(key), new TypeReference<List<Map<String, List<String>>>>() {
            });
            if (!CollectionUtils.isEmpty(mapList)) {
                Map<String, List<String>> maps = mapList.get(0);
                if (StringUtils.isNotEmpty(address.getTown()) && maps.get(address.getTown()) != null) {
                    List<String> fifthAreas = maps.get(address.getTown());
                    for (String value : fifthAreas) {
                        if (!StringUtil.isEmpty(addr) && addr.contains(value)) {
                            cartVO.setAllowCreateOrder(false);
                            cartVO.setDispatchMsg("【不支持快递到家】:收货地址黑名单,"+addr);
                        }
                    }
                }else{
                    List<String> forthAreas = maps.get("空")==null?new ArrayList<>(): maps.get("空");
                    for (String value : forthAreas) {
                        if (!StringUtil.isEmpty(addr) && addr.contains(value)) {
                            cartVO.setAllowCreateOrder(false);
                            cartVO.setDispatchMsg("【不支持快递到家】:收货地址黑名单,"+addr);
                        }
                    }
                }
            }
        }
    }

    private MemberAddress getUserCurrentAddress() {
        Integer addressId = checkoutParamManager.getParam().getAddressId();
        if(addressId==null){
           return null;
        }
        MemberAddress address = memberAddressClient.getModel(addressId);
        Buyer buyer = UserContext.getBuyer();
        if (address == null || !address.getMemberId().equals(buyer.getUid())) {
            return null;
        }
        return address;
    }

    /**
     * 校验地区
     *
     * @param cartList 购物车
     * @param areaId   地区
     * @return
     */
    @Override
    public List<CacheGoods> checkArea(List<CartVO> cartList, Integer areaId) {
        List<CacheGoods> errorGoods = new ArrayList<>();
        for (CartVO cartVo : cartList) {
            //运费模版映射
            Map<Integer, ShipTemplateChildDTO> shipMap = new HashMap<>(16);
            List<CartSkuVO> cartSkuVOS = cartVo.getSkuList();
            for (CartSkuVO skuVO : cartSkuVOS) {
                // 未选中则先不处理
                if (skuVO.getChecked() == 0) {
                    continue;
                }
                // 快递统一运费
                if (skuVO.getFreightPricingWay() != null && skuVO.getFreightPricingWay() == 0) {
                    continue;
                }
                // 不免运费
                if (skuVO.getIsFreeFreight()!=null && skuVO.getIsFreeFreight() != 1 && skuVO.getIsGlobal()!=null && skuVO.getIsGlobal() == 1) {
                    skuVO.setIsShip(1);
                    // 快递统一运费
                    if (skuVO.getFreightPricingWay() != null && skuVO.getFreightPricingWay() == 0) {
                        continue;
                    }
                    // 获取运费模板信息 没有运费模版的话 记录错误的商品，禁止下单
                    ShipTemplateVO temp = this.shipTemplateClient.get(skuVO.getTemplateId());
                    //如果模版空
                    if (temp == null) {
                        errorGoods.add(goodsClient.getFromCache(skuVO.getGoodsId()));
                        skuVO.setIsShip(0);
                    } else {

                        for (ShipTemplateChildBuyerVO child : temp.getItems()) {
                            if (child.getAreaId() != null) {
                                /** 校验地区 */
                                if (child.getAreaId().indexOf("," + areaId + ",") >= 0) {
                                    ShipTemplateChildDTO dto = new ShipTemplateChildDTO(child);
                                    dto.setType(temp.getType());
                                    shipMap.put(skuVO.getSkuId(), dto);
                                }
                            }
                        }
                        // 如果没有匹配 则当
                        if (!shipMap.containsKey(skuVO.getSkuId())) {
                            errorGoods.add(goodsClient.getFromCache(skuVO.getGoodsId()));
                            skuVO.setIsShip(0);
                            cartVo.setAllowCreateOrder(false);
                        }
                    }
                } else {
                    //如果没有设置运费模版 则默认地区有货
                    skuVO.setIsShip(1);
                }
            }
            cartVo.setShipTemplateChildMap(shipMap);
        }
        return errorGoods;
    }

    /**
     * 同城配送费用计算
     *
     * @param cartList
     */
    @Override
    public void setLocalShippingPrice(List<CartVO> cartList) {
        // TODO 【社区团购】社区团购店铺商品支持自提，无需校验配送方式

        for (CartVO cartVo : cartList) {
            if (cartVo.getAllowLocal() == 1) {
                // 同城配送 费用和时间计算
                ShipCalculateDTO shipCalculateDTO = this.getLocalShipPrice(cartVo);

                Double localShipPrice = shipCalculateDTO.getLocalShipPrice()!= null ? Double.valueOf(shipCalculateDTO.getLocalShipPrice().toString()) : 0D;
                String localShipTime = StringUtils.isNotBlank(shipCalculateDTO.getLocalEndTime()) ? shipCalculateDTO.getLocalEndTime() : null;

                cartVo.getPrice().setLocalFreightPrice(localShipPrice);
                cartVo.getPrice().setLocalFreightTime(localShipTime);
                cartVo.setShippingTypeName("同城配送费");
            } else {
                // 如果不支持快递配送 需要设置默认数据
                cartVo.setShippingTypeName("不支持同城");
            }

        }

    }

    private ShipCalculateDTO getLocalShipPrice(CartVO cartVo) {
        ShipCalculateDTO shipCalculateDTO = new ShipCalculateDTO();
        if(cartVo.getShipLocalTemplateVO() != null){
            shipCalculateDTO.setTemplateFeeSetting(cartVo.getShipLocalTemplateVO().getFeeSettingVO());
            shipCalculateDTO.setTemplateTimeSetting(cartVo.getShipLocalTemplateVO().getTimeSettingVO());
            shipCalculateDTO.setDistance(cartVo.getDistance());
            shipFeeCalculator.calculate(shipCalculateDTO);
            shipTimeCalculator.calculate(shipCalculateDTO);
        }
        return shipCalculateDTO;
    }


    /**
     * 归一化 店铺可供选择的配送方式和用户默认可使用配送方式
     *
     * @param cartList
     */
    @Override
    public void checkShipWay(List<CartVO> cartList) {
        debugger.log("【配送检查 ：】" + cartList.toString());
        // 用户收货地址
        MemberAddress address = getUserCurrentAddress();

        // 用户选择的默认配送方式
        List<ShipWayVO> shipWays = checkoutParamManager.getParam().getShipWays();
        List<ShipWayVO> newShipWays = new ArrayList<>();
        Map<Integer, ShipWayVO> shipWayMap = CollectionUtils.isEmpty(shipWays) ?
                Maps.newHashMap() : shipWays.stream().distinct().collect(Collectors.toMap(ShipWayVO::getSellerId, Function.identity()));

        // 未选中结算商品
        List<CartVO> uncheckCartList = new ArrayList<>();
        // 遍历店铺sku
        for (CartVO cartVO : cartList) {
            String cartSourceType = cartVO.getCartSourceType();
            // 店铺支持配送类型 本地同城 快递配送 用户自提  （是否允许计算运费）
            int allowLocal = 0;
            int allowGlobal = 0;
            int allowSelf = 0;
            String shipWay = shipWayMap.get(cartVO.getSellerId())==null?ShipTypeEnum.SELF.name():shipWayMap.get(cartVO.getSellerId()).getShipWay();
            if(cartSourceType.equals(CartSourceType.SHETUAN_CART.name()) && shipWay.equals(ShipTypeEnum.GLOBAL.name()) && address==null){
                throw new ServiceException("500","快递到家,收货地址不能为空!");
            }
            List<CartSkuVO> skuList = cartVO.getSkuList();
            // 商品级别
            Double totalGoodsPrice = 0.0;
            List<CartSkuVO> uncheckCartSkuList = new ArrayList<>();
            // 过滤sku配送方式和商品总价汇总
            for (CartSkuVO cartSkuVO : skuList) {
                // 购物车商品是否选中结算
                if (CartType.CHECKOUT.equals(cartVO.getCartType()) && cartSkuVO.getChecked() == 0) {
                    uncheckCartSkuList.add(cartSkuVO);
                    continue;
                }
                // 是否配置快递模板 【默认买家承担运费  卖家承担运费TemplateId=0】
                if (cartSkuVO.getIsGlobal()!=null && cartSkuVO.getIsGlobal() == 1) {
                    allowGlobal = 1;
                }else{
                    cartVO.setDispatchMsg("【不支持快递到家】："+allowGlobal+"-----"+cartSkuVO.toString());
                }
                // 是否配置同城配送模板
                if (cartSkuVO.getIsLocal()!=null && cartSkuVO.getIsLocal() ==1) {
                    allowLocal = 1;
                }
                // 是否配置自提配送
                if (cartSkuVO.getIsSelfTake()!=null && cartSkuVO.getIsSelfTake() == 1) {
                    allowSelf = 1;
                }
                totalGoodsPrice += cartSkuVO.getPurchasePrice() * cartSkuVO.getNum();
            }

            // 设置单个店铺购物车可支持配送方式
            cartVO.setAllowLocal(allowLocal);
            cartVO.setAllowGlobal(allowGlobal);
            cartVO.setAllowSelf(allowSelf);

            // 优惠前商品总金额
            cartVO.setTotalGoodsPrice(totalGoodsPrice);

            // 去除未选中店铺商品
            if (uncheckCartSkuList.size() == skuList.size()) {
                uncheckCartList.add(cartVO);
                continue;
            } else if (uncheckCartSkuList.size() > 0) {
                skuList.removeAll(uncheckCartSkuList);
            }
        }

        // 去除未选中店铺
        if (uncheckCartList.size() > 0) {
            cartList.removeAll(uncheckCartList);
        }

        for (CartVO cartVO : cartList) {
            // 支持同城 但是同城配送是否满足 起送费和配送距离
            if (cartVO.getAllowLocal() == 1) {
                shipTemplateClient.checkLocalCart(cartVO, address);
            }

            // 店铺不支持任何一种配送方式
            if (cartVO.getAllowLocal() == 0 && cartVO.getAllowGlobal() == 0 && cartVO.getAllowSelf() == 0) {
//                throw new ServiceException(TradeErrorCode.E480.code(), "【" + cartVO.getSellerName() + "】,所属商品不支持自提或快递或同城配送,请及时联系团长!");
                  throw new ServiceException(TradeErrorCode.E480.code(), cartVO.getErrorMsg());
            }

            // 由于业务结构设计 快递费用计算在前 设置freight-price  freight--》》》globalFreight  以下代码顺序不能改
            ShipWayVO shipWay = getDefaultShipWay(shipWayMap, cartVO);
            shipWay.setShipWay(cartVO.getActiveShipWay());
            newShipWays.add(shipWay);
        }
         //重置check-params中的shipWay
        checkoutParamManager.setShipWay(newShipWays);


    }

    /**
     * 用户默认配送方式
     *
     * @param shipWayMap
     * @param cartVO
     * @return
     */
    private ShipWayVO getDefaultShipWay(Map<Integer, ShipWayVO> shipWayMap, CartVO cartVO) {
        // 用户历史默认配送方式
        ShipWayVO shipWay = shipWayMap.get(cartVO.getSellerId());
        // 不存在设置默认值 快递配送
        if (shipWay == null) {
            shipWay = new ShipWayVO();
            shipWay.setSellerId(cartVO.getSellerId());
            shipWay.setShipWay("GLOBAL");
            shipWayMap.put(cartVO.getSellerId(), shipWay);
        }


        // 同城配送
        if (shipWay.getShipWay().equals("LOCAL") && cartVO.getAllowLocal() == 1) {
            cartVO.setActiveShipWay("LOCAL");
            return shipWay;
        }

        // 自提
        if (shipWay.getShipWay().equals("SELF") && cartVO.getAllowSelf() == 1) {
            cartVO.getPrice().setFreightPrice(0.0);
            cartVO.setActiveShipWay("SELF");
            return shipWay;
        }

        // 快递
        if (shipWay.getShipWay().equals("GLOBAL") && cartVO.getAllowGlobal() == 1) {
            cartVO.setActiveShipWay("GLOBAL");
        }

        // 用户历史默认配送方式与当前店铺商品配送不匹配 需要重新选择   : 层级 同城配送--->>>同城自提--->>>快递配送
        if (cartVO.getActiveShipWay() == null) {
            if (cartVO.getAllowGlobal() == 1) {
                cartVO.setActiveShipWay("GLOBAL");
            } else if (cartVO.getAllowSelf() == 1) {
                cartVO.setActiveShipWay("SELF");
            } else if (cartVO.getAllowLocal() == 1) {
                cartVO.setActiveShipWay("LOCAL");
            }
        }

        if (cartVO.getActiveShipWay().equals("GLOBAL")) {
            // TODO 设置快递配送费用
            cartVO.getPrice().setGlobalFreightPrice(cartVO.getPrice().getFreightPrice());
        }
        if (cartVO.getActiveShipWay().equals("LOCAL")) {
            // TODO 设置同城配送费用
            cartVO.getPrice().setFreightPrice(cartVO.getPrice().getLocalFreightPrice());
        }

        return shipWay;
    }
}
